package yxy.game.pm2.command.union;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionMessage;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.UnionLog;

import java.util.Collection;

/** 联盟 联盟日志 */
@MessageType(proto = Command.UnionLogInfo, classtype = UnionMessage.UnionLogInfoRequest.class)
public class CMD_UnionLogInfo extends Command<UnionMessage.UnionLogInfoRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionMessage.UnionLogInfoRequest request) {
		String playerCode = messageSource.getTag();

		UnionMessage.UnionLogInfoResponse.Builder response = UnionMessage.UnionLogInfoResponse.newBuilder();

		// 检查是否已经有联盟
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnion(entry);
		if (!result.equals(Result.UnionIn)) {
			send(messageSource, response, result);
			return;
		}
		Collection<UnionLog> logs = UnionLog.all(entry.getUnionBean().getCode());

		for (UnionLog log : logs) {
			UnionMessage.UnionLog.Builder builder = UnionMessage.UnionLog.newBuilder();
			builder.setTime(log.getTime().getMillis());
			builder.setText(log.getText());
			response.addLogs(builder);
		}

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, UnionMessage.UnionLogInfoResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}